/* 
 *  Document   : extension      一些原始类型和操作扩展
 *  Created on : 2011-5-30, 11:59:51
 *  Author     : GodSon
 *  Email      : wmails@126.com
 *  Link       : http://www.btboys.com
 *  Vsersion   : 0.1 
 */
   
/**
 * 原始类型扩展
 */
String.prototype.trim=function () {  
    return this.replace(/(^[\t\n\r]*)|([\t\n\r]*$)/g,'');  
};  

String.prototype.ltrim=function () {  
    return this.replace(/^[\t\n\r]/g,'');  
};  

String.prototype.rtrim=function () {  
    return this.replace(/[\t\n\r]*$/g,'');  
};  

String.prototype.endsWith = function(str){	
    if(this.length==0 || !str || typeof str !='string') return false;
    if(str.length > this.length) return false;
    return (this.substring(this.length-str.length)==str)?true:false;
}

String.prototype.startsWith = function(str){	
    if(this.length==0 || !str || typeof str !='string') return false;
    if(str.length > this.length) return false;
    return this.substr(0,str.length)==str?true:false;  
}

String.prototype.toNumber = function(defaultNum){	
    return isNaN(this)?(defaultNum?Number(defaultNum):0):Number(this);
};

Date.isLeapYear = function(year){
    return (((year%4===0)&&(year%100!==0))||(year%400===0));
};

Date.prototype.equals = function(date,type){
    return this.compare(date,type)==0;
};

//扩展Date类型，时间格式化
Date.prototype.format = function(format){
    /*
     * eg:format="yyyy-MM-dd hh:mm:ss";
     */
    if(!format){
        format = "yyyy-MM-dd hh:mm:ss";
    }

    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
    // millisecond
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) { 
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/**
 * 扩展jquray对form表单的操作
 */
(function($) {
    $.fn.formToArray = function(semantic) {
        var a = [];
        if (this.length === 0) {
            return a;
        }
        var form = this[0];
        var els = semantic ? form.getElementsByTagName('*') : form.elements;
        if (!els) {
            return a;
        }
        var i,j,n,v,el,max,jmax;
        for(i=0, max=els.length; i < max; i++) {
            el = els[i];
            n = el.name;
            if (!n) {
                continue;
            }

            if (semantic && form.clk && el.type == "image") {
                // handle image inputs on the fly when semantic == true
                if(!el.disabled && form.clk == el) {
                    a.push({
                        name: n, 
                        value: $(el).val()
                    });
                    a.push({
                        name: n+'.x', 
                        value: form.clk_x
                    }, {
                        name: n+'.y', 
                        value: form.clk_y
                    });
                }
                continue;
            }

            v = $.fieldValue(el, true);
            if (v && v.constructor == Array) {
                for(j=0, jmax=v.length; j < jmax; j++) {
                    a.push({
                        name: n, 
                        value: v[j]
                    });
                }
            }
            else if (v !== null && typeof v != 'undefined') {
                a.push({
                    name: n, 
                    value: v
                });
            }
        }

        if (!semantic && form.clk) {
            // input type=='image' are not found in elements array! handle it here
            var $input = $(form.clk), input = $input[0];
            n = input.name;
            if (n && !input.disabled && input.type == 'image') {
                a.push({
                    name: n, 
                    value: $input.val()
                });
                a.push({
                    name: n+'.x', 
                    value: form.clk_x
                }, {
                    name: n+'.y', 
                    value: form.clk_y
                });
            }
        }
        return a;
    };

    $.fn.formJsonSerialize = function(semantic) {
        //hand off to jQuery.param for proper encoding
        var s = {};
        $.each(this.formToArray(semantic),function(i,v){
            s[v.name] = v.value;
        });
        return s;
    };

    $.fn.formSerialize = function(semantic) {
        //hand off to jQuery.param for proper encoding
        return $.param(this.formToArray(semantic));
    };

    $.fn.fieldSerialize = function(successful) {
        var a = [];
        this.each(function() {
            var n = this.name;
            if (!n) {
                return;
            }
            var v = $.fieldValue(this, successful);
            if (v && v.constructor == Array) {
                for (var i=0,max=v.length; i < max; i++) {
                    a.push({
                        name: n, 
                        value: v[i]
                    });
                }
            }
            else if (v !== null && typeof v != 'undefined') {
                a.push({
                    name: this.name, 
                    value: v
                });
            }
        });
        //hand off to jQuery.param for proper encoding
        return $.param(a);
    };

    $.fn.fieldValue = function(successful) {
        for (var val=[], i=0, max=this.length; i < max; i++) {
            var el = this[i];
            var v = $.fieldValue(el, successful);
            if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
                continue;
            }
            v.constructor == Array ? $.merge(val, v) : val.push(v);
        }
        return val;
    };

    $.fieldValue = function(el, successful) {
        var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
        if (successful === undefined) {
            successful = true;
        }

        if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
            (t == 'checkbox' || t == 'radio') && !el.checked ||
            (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
            tag == 'select' && el.selectedIndex == -1)) {
            return null;
        }

        if (tag == 'select') {
            var index = el.selectedIndex;
            if (index < 0) {
                return null;
            }
            var a = [], ops = el.options;
            var one = (t == 'select-one');
            var max = (one ? index+1 : ops.length);
            for(var i=(one ? index : 0); i < max; i++) {
                var op = ops[i];
                if (op.selected) {
                    var v = op.value;
                    if (!v) { // extra pain for IE...
                        v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                    }
                    if (one) {
                        return v;
                    }
                    a.push(v);
                }
            }
            return a;
        }
        return $(el).val();
    };

    $.fn.clearForm = function() {
        return this.each(function() {
            $('input,select,textarea', this).clearFields();
        });
    };

    $.fn.clearFields = $.fn.clearInputs = function() {
        return this.each(function() {
            var t = this.type, tag = this.tagName.toLowerCase();
            if (t == 'text' || t == 'password' || tag == 'textarea') {
                this.value = '';
            }
            else if (t == 'checkbox' || t == 'radio') {
                this.checked = false;
            }
            else if (tag == 'select') {
                this.selectedIndex = -1;
            }
        });
    };

    $.fn.resetForm = function() {
        return this.each(function() {
            // guard against an input with the name of 'reset'
            // note that IE reports the reset function as an 'object'
            if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
                this.reset();
            }
        });
    };

    $.fn.enable = function(b) {
        if (b === undefined) {
            b = true;
        }
        return this.each(function() {
            this.disabled = !b;
        });
    };

    $.fn.selected = function(select) {
        if (select === undefined) {
            select = true;
        }
        return this.each(function() {
            var t = this.type;
            if (t == 'checkbox' || t == 'radio') {
                this.checked = select;
            }
            else if (this.tagName.toLowerCase() == 'option') {
                var $sel = $(this).parent('select');
                if (select && $sel[0] && $sel[0].type == 'select-one') {
                    // deselect all other options
                    $sel.find('option').selected(false);
                }
                this.selected = select;
            }
        });
    };
})(jQuery);

//easyui window扩展
(function($){
    /**
	 * 创建UUID
	 */
    function S4() {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    /**
	 * 生成windowId
	 */
    function  CreateIndentityWindowId(){
        return "UUID-"+(S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
    }
    /**
	 * 销毁
	 */
    function destroy(target){
        var options = $(target).dialog("options");
        if(options.fck){
            $("body").children("iframe").remove();
            KE.remove(options.fck.id);
        }
        if(options.ke){
            KE.remove(options.ke.id);
        }
        $(target).dialog("destroy");
    }
	
    /**
	 * 获取当前操作的window 
	 *  @param target 当前窗口的windowId 或者 当前窗口中的元素(element)
	 */
    function getWindow(target){
        if(typeof target == "string"){
            return document.getElementById(target);
        }else{
            return $(target).parents(".window-body");
        }
    }
	
    //入口方法
    $.createWin = function(options){
        if(!options.url && !options.contents){
            $.messager.alert("提示","缺少必要参数!(url or content)");
            return false;
        }
		
        var windowId = CreateIndentityWindowId();
		
        if(options.winId){
            windowId=options.winId;
        }
		
        //如果存在buttons(请看easyui对buttons的定义)，默认添加关闭按钮
        if(options.buttons){
            var closeBtn = {
                text:'关闭',
                handler:function(){
                    $("#"+windowId).dialog("destroy");
                }
            };
            options.buttons.push(closeBtn);
        }
		
        options = $.extend({},$.createWin.defaults, options || {});
		
        if(options.contents){
            ajaxSuccess(options.contents);
        }else{
            if(!options.isIframe){
                $.ajax({
                    url:options.url,
                    type:"POST",
                    data:options.data == null ? "" : options.data,
                    success:function(date){
                        ajaxSuccess(date);
                    },
                    error:function(){
                        $.messager.alert("提示","加载失败！");
                    }
                });
            }else{
                ajaxSuccess();
            }
        }
        return windowId;
		
        /**
		 * 页面加载成功处理
		 */
        function ajaxSuccess(date){
            var dialog  = $('<div id="'+windowId+'"></div>');
            if(options.target != 'body'){
                options.inline = true;
            }
            dialog.appendTo($(options.target));
            dialog.dialog(options);
            
           if(options.isIframe && !date){
                dialog.find("div.dialog-content").html('<iframe width="100%" height="100%" frameborder="0" src="'+options.url+'" ></iframe>');
            }else{
               dialog.find("div.dialog-content").html(date);
            }
            $.parser.parse(dialog);

            options.onComplete.call(this,windowId);									//创建成功后回调函数
            //可以整合fck的显示
            // options.fck:{
            // 		"id":textAreaIdORtextAreaName,
            //  	"height":fckHeight
            // }
            if(options.fck){
                CKEDITOR.replace(options.fck.id,{
                    height:options.fck.height
                });
            }
            //可以整合KindEditor的显示
            // options.ke:{
            // 		"id":textAreaId
            // }
            if(options.ke){
                KE.init(options.ke);
                KE.create(options.ke.id);
            }
        }
    };
	
    //关闭并销毁实体
    $.fn.destroy =function(){
        destroy(this);
    };
	
    window.GETWIN = getWindow;
	
    //默认参数
    $.createWin.defaults = $.extend({},$.fn.dialog.defaults,{
        url:'',					//窗口要加载的html片段地址
        data:'',				//可带参数，data类型为jqurey.ajax的data参数类型
        target:'body',				//指定窗口打开的区域,是一个jq的选择器，例如#id
        isIframe:false,			//如果存在url，是否在iframe里面打开url
        zIndex: 100000,			
        height : 200,
        width : 400,
        collapsible: false,
        minimizable: false,
        maximizable: false,
        closable: true,
        modal:true,
        onClose:function(){
            destroy(this);
        },
        onMove:function(left,top){
            var opts = $.data(this, 'panel').options;
            if(top < 0){
                $(this).dialog("move",{
                    "left":left,
                    "top":0
                });
            }else if(opts.maximized){
                $(this).dialog("restore");
                $(this).dialog("move",{
                    "left":left+100,
                    "top":top
                });
            }
            if(top > ($(opts.target).height()-20)){
                $(this).dialog("move",{
                    "left":left,
                    "top":($(opts.target).height()-25)
                    });
            }
        },
        onComplete:function(windowId){}	//创建成功后的回调方法		
    });
})(jQuery);

//navigationc导航插件
(function($){
    function init(target){
        if($(target).attr("class") == "navigation-sep"){
            $(target).html("&nbsp;"); 
            return;
        }        
        var opts = $.data(target, 'navigation').options;
        $(target).addClass("easyui-navigation-item").hover(function(){
            $(this).addClass("easyui-navigation-over");
        },function(){
            $(this).removeClass("easyui-navigation-over");
        }).click(function(){
            if(!opts.parent){
                var p =  $(target).closest("div.easyui-navigation");
                p.find(".easyui-navigation-select").removeClass("easyui-navigation-select");
                $(this).addClass("easyui-navigation-select");
                if(opts.onClick)
                    opts.onClick.call(this,opts);
            }else{
                var lef = $(target).children().eq(0);
                if(lef.text() == "+"){
                    lef.text("-");
                    $("div[parentTarget="+opts.parent+"]").slideDown();
                }else{
                    lef.text("+");
                    $("div[parentTarget="+opts.parent+"]").slideUp();
                }
            }
        });
        
        var span = $('<span class="l-btn-text"></span>').text(opts.title);
        if(opts.iconCls) span.addClass(opts.iconCls).css("padding","2px 0 2px 20px");
        
        $(target).html(span);
        if(opts.parent){
            var children = $("<div/>").attr("parentTarget", opts.parent).css("display",!opts.open ? "none" : "block");
        
            $(target).prepend("<span>"+(!opts.open ? "+" : "-")+"</span>").after(children);
        }   
        if(opts.ptarget)   $(target).appendTo($("div[parentTarget="+opts.ptarget+"]")).prepend("<span>&nbsp;&nbsp;</span>");
    }
    
    function parseOptions(target){
        var t = $(target);
        return {
            iconCls: (t.attr('iconCls') || undefined),
            href: (t.attr('href') || undefined),
            title:(t.attr('title') || "标题"),
            parent:(t.attr('parent') || false),
            ptarget:(t.attr('ptarget') || false),
            open:(t.attr('expand') || false)
        };
    }
        
    $.fn.navigation = function(options,param){     
        if (typeof options == 'string'){
        //TODO方法
        }
        options = options || {};
        return this.each(function(){
            $(this).panel({
                fit:true,
                border:false,
                bodyCls:"easyui-navigation"
            });
            var items = $(this).children();
            items.each(function(){
                var state = $.data(this, 'navigation');
                if (state){
                    $.extend(state.options, options);
                } else {
                    state = $.data(this, 'navigation', {
                        options: $.extend({}, $.fn.navigation.defaults, parseOptions(this), options)
                    });
                }
                init(this); 
            });
        });
    }
    $.fn.navigation.defaults = {
        onClick:function(opt){}
    };
    
    $.parser.plugins.push("navigation");
})(jQuery);

/**
 * @param {Object} options
 * return windowId
*/
(function($){
    
    /**
	 * 创建UUID
	 */
    function S4() {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    /**
	 * 生成windowId
	 */
    function  CreateIndentityWindowId(){
        return "UUID-"+(S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
    }
	
    function HasOpen(title){
        var allOpen = $('.appToolbar');
        var hasapp = false;
        allOpen.each(function(i,v){
            if($(this).text() == title){
                hasapp = this.id;
            }
        });
        return hasapp;
    }
	
    //入口方法
    $.fn.openApp = function(){
        var windowId = CreateIndentityWindowId();
        var app = $(this).data("app");
        var ishase = HasOpen(app.text);
        if(ishase){
            $("#"+ishase.split("_")[1]).dialog('open')
        }else{
            var dialog = $('<div id="'+windowId+'"></div>');
            $('.GD_windBody').append(dialog);
            var oapps = $('.GD_windBody > div.window');

            var T = oapps.length*25+10;
            var L = oapps.length*25+300;
                        
            var dconif = {
                title:app.text,
                height:400,
                width:700,
                top:T,
                left:L,
                resizable:true,
                maximizable:true,
                minimizable:true,
                inline:true,
                cache:false,
                shadow:false,
                onClose:function(){
                    $(this).dialog("destroy");
                    $('#App_'+this.id).remove();
                    RIA.getNs("os").ChangeToolbarWinList("");
                },
                onMinimize:function(){
                    if($(this).prev('.window-header').find('.panel-tool-restore').length == 1){
                        var opts = $.data(this, 'panel').options;
                        opts.maximized = true;
                    }
                    $('#App_'+this.id).attr('state','min');
                },
                onMove:function(left,top){
                    var opts = $.data(this, 'panel').options;
                    if(top < 0){
                        $(this).dialog("move",{
                            "left":left,
                            "top":0
                        });
                        $(this).dialog("maximize");
                    }else if(opts.maximized){
                        $(this).dialog("restore");
                        $(this).dialog("move",{
                            "left":left+100,
                            "top":top
                        });
                    }
                    if(top > $('.GD_windBody').height()){
                        $(this).dialog("move",{
                            "left":left,
                            "top":($('.GD_windBody').height()-25)
                            });
                    }
                }
            };
            if(app.href && !/^http/i.test(app.href)){
                dconif.href = app.href;
            }
            dialog.dialog(dconif);
                        
            if(app.href && /^http/i.test(app.href)){
                dialog.find('.dialog-content').html('<iframe name="appLink" width="100%" height="100%" frameborder="0" src="'+app.href+'" ></iframe>');
            }
                         
            $(dialog).click(function(){
                $(this).dialog('open')
                });
			
            var appFoot = $('<div class="appToolbar_Foot" id="App_'+windowId+'" state = "open"></div>').click(function(){
                var opts = $.data($("#"+this.id.split("_")[1])[0], 'panel').options;
                var panel = $.data($("#"+this.id.split("_")[1])[0], 'panel').panel;
                if($(this).attr('state') == "min"){
                    panel.show();
                    opts.minimized = false;
                    $(this).attr('state','open');
                }else{
                    panel.hide();
                    opts.minimized = true;
                    $(this).attr('state','min');
                }					
            });
            var tool = $("<div id='Menu_"+windowId+"' class='appToolbar'>"+app.text+"</div>").hover(function(){
                $(this).addClass("appToolbar-hover");
            },function(){
                $(this).removeClass("appToolbar-hover");
            });
			
            appFoot.append(tool);
            $("#GD_WinList").append(appFoot);
        }
    };
})(jQuery);